package com.example.recyclerviewtest;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class FruitAdapter_StaggeredGridLayout extends RecyclerView.Adapter<FruitAdapter_LinearLayout.ViewHolder>{

    private List<Fruit> mFruitList;

    //定义一个内部类ViewHolder，它继承自RecyclerView.ViewHolder。
    //ViewHolder的构造函数中传入一个View参数，该参数表示RrcyclerView子项的最外层布局，
    // 然后就可以通过findViewById获取布局中的实例。
    static class ViewHolder extends RecyclerView.ViewHolder {

        ImageView fruitImage;
        TextView fruitName;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            fruitImage=itemView.findViewById(R.id.fruit_image);
            fruitName=itemView.findViewById(R.id.fruit_text);
        }
    }

    //FruitAdapter的构造函数，用于传入数据源
    public FruitAdapter_StaggeredGridLayout(List<Fruit> fruitList){
        mFruitList=fruitList;
    }

    @NonNull
    @Override
    //用于创建ViewHolder实例。
    //将fruit_item布局加载进来，然后创建ViewHolder实例，将加载的布局传到构造函数中，返回ViewHolder实例。
    public FruitAdapter_LinearLayout.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item_staggered_grid_layout,parent,false);
        FruitAdapter_LinearLayout.ViewHolder holder=new FruitAdapter_LinearLayout.ViewHolder(view);
        return holder;
    }

    @Override
    //用于对RecyclerView子项进行赋值，会在每个子项滚动到屏幕里时执行。
    //通过position获得当前项的Fruit实例，然后将数据设置在FruitAdapter.ViewHolder中的ImageView、TextVIew中。
    public void onBindViewHolder(@NonNull FruitAdapter_LinearLayout.ViewHolder holder, int position) {
        Fruit fruit=mFruitList.get(position);
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());

    }

    @Override
    //获取RecyclerView的子项长度
    public int getItemCount() {
        return mFruitList.size();
    }


}
